package com.coco.common.advice;

import com.coco.common.annotation.IngoreResponseAdvice;
import com.coco.common.constant.Constant;
import com.coco.common.result.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author minicoco
 * @version 1.0
 * @date 2021/7/14 22:29
 * controller统一返回处理
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice {

    /**
     * 设置是否拦截
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //判断是否要执行返回拦截
        //判断类上是否有忽略标识
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IngoreResponseAdvice.class)) {
            return false;
        }
        //判断方法上是否有忽略标识
        return !methodParameter.getMethod().isAnnotationPresent(IngoreResponseAdvice.class);
    }

    /**
     * 执行返回拦截的逻辑
     *
     * @param body
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //创建统一返回对象
        CommonResponse<Object> success = new CommonResponse<>(Constant.ResultCode.DEFAULT_SUCCESS, "success");
        //判断返回题类型
        if (body == null) {
            return success;
        } else if (body instanceof CommonResponse) {
            success = (CommonResponse<Object>) body;
        } else {
            success.setData(body);
        }
        return success;
    }
}
